package ch.lue.tvsedit.model;

import java.util.ArrayList;
import java.util.Vector;

import javax.swing.DefaultListModel;
import javax.swing.ListModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;



public class TVSModel implements ContentHandler
{
	private ChannelGroup actualGroup;
	private Channel actualChannel;
	private DefaultListModel groups;
	private ChannelTable channels;
	
	public TVSModel()
	{
		groups = new DefaultListModel();
		channels = new ChannelTable();
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		
	}

	@Override
	public void endDocument() throws SAXException {
	}

	@Override
	public void endElement(String uri, String localName, String name)
			throws SAXException {
		if(name.equals("channelgroup"))
		{
			actualGroup = null;
		}
	}

	@Override
	public void endPrefixMapping(String prefix) throws SAXException {
		
	}

	@Override
	public void ignorableWhitespace(char[] ch, int start, int length)
			throws SAXException {
		
	}

	@Override
	public void processingInstruction(String target, String data)
			throws SAXException {
		
	}

	@Override
	public void setDocumentLocator(Locator locator) {
		
	}

	@Override
	public void skippedEntity(String name) throws SAXException {
	}

	@Override
	public void startDocument() throws SAXException {
		
	}

	@Override
	public void startElement(String uri, String localName, String name,
			Attributes atts) throws SAXException {
		if(name.equals("channelgroup"))
		{
			actualGroup = new ChannelGroup(atts.getValue("GroupName"), Integer.parseInt(atts.getValue("SortOrder")));
			groups.addElement(actualGroup);
		}
		
		if(name.equals("channel"))
		{
			actualChannel = new Channel(atts.getValue("Name"), atts);
			channels.add(actualChannel);
		}
		
		
		if(name.equals("map"))
		{
			if(actualGroup != null)
			{
				try
				{
					actualGroup.addChannel(atts.getValue("ChannelName"), Integer.parseInt(atts.getValue("SortOrder")));
				}
				catch (Exception e) 
				{
					actualGroup.addChannel(atts.getValue("ChannelName"));
				}
			}
			
			if(actualChannel != null)
			{
				actualChannel.setMappingDetails(atts);
			}
		}
		
		if(name.equals("tune"))
		{
			if(actualChannel != null)
			{
				actualChannel.setTuningDetails(atts);
			}
		}
	}

	@Override
	public void startPrefixMapping(String prefix, String uri)
			throws SAXException {
		
	}
	
	public TableModel getChannelModel() 
	{
		return channels;
	}
	
	public DefaultListModel getGroupModel()
	{
		return groups;
	}
}
